package com.tanhua.autoconfig.template;

import cn.hutool.core.collection.CollUtil;
import com.easemob.im.server.EMProperties;
import com.easemob.im.server.EMService;
import com.easemob.im.server.model.EMTextMessage;
import com.tanhua.autoconfig.properties.HuanXinProperties;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.crypto.agreement.DHUnifiedAgreement;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Locale;
import java.util.Set;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/12/4 20:06
 */
@Slf4j
public class HuanXinTemplate {

    private EMService service;

    @Autowired
    private HuanXinProperties hunaxinProperties;


    public HuanXinTemplate(HuanXinProperties huanXinProperties){
        EMProperties properties = EMProperties.builder()
                .setAppkey(huanXinProperties.getAppkey())
                .setClientId(huanXinProperties.getClientId())
                .setClientSecret(huanXinProperties.getClientSecret())
                .build();
        // 给成员赋值
        service = new EMService(properties);
    }

    // 创建用户
    public boolean creatUser(String username, String password){

        try {
            service.user().create(username.toLowerCase(), password).block();
            return true;
        }catch (Exception e){
            e.printStackTrace();
            log.error("创建环信用户失败");
        }
        return false;
    }

    // 添加联系人
    public boolean addContact(String username1, String username2){

        try {
            service.contact().add(username1, username2).block();
            return true;
        }catch (Exception e){
            e.printStackTrace();
            log.error("添加联系人失败");
        }
        return false;
    }

    // 删除联系人
    public boolean removeContact(String username1, String username2){

        try {
            service.contact().remove(username1, username2).block();
            return true;
        }catch (Exception e){
            e.printStackTrace();
            log.error("删除联系人失败");
        }
        return false;
    }


    // 发送消息
    public boolean sendMsg(String username, String content){

        try {
            Set<String> set = CollUtil.newHashSet(username);
            EMTextMessage message = new EMTextMessage().text(content);
            service.message().send("admin", "users", set, message, null).block();
            return true;
        }catch (Exception e){
            e.printStackTrace();
            log.error("发送消息失败");
        }
        return false;
    }


}
